package com.liaoban.app.ui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.liaoban.app.R;
import com.liaoban.app.api.type.User;
import com.liaoban.app.api.type.event.LocationEvent;
import com.liaoban.app.api.type.event.LoginEvent;
import com.liaoban.app.api.type.request.BdingReq;
import com.liaoban.app.api.type.request.SmsRequest;
import com.liaoban.app.biz.CommonBiz;
import com.liaoban.app.constants.ExtraParam;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.ui.base.BaseToolbarActivity;
import com.liaoban.app.util.CommonUtils;
import com.liaoban.app.util.VerifyUtil;
import com.liaoban.app.widget.ClearEditText;
import com.liaoban.app.widget.MyTextWatcher;
import com.netease.nim.demo.DemoCache;
import com.netease.nim.demo.config.preference.Preferences;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.LoginInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by ybc on 2018/7/6 0006.
 * 绑定
 */
public class BindActivity extends BaseToolbarActivity {

    @BindView(R.id.et_phone)
    ClearEditText etPhone;
    @BindView(R.id.et_ver_code)
    EditText etVerCode;
    @BindView(R.id.tv_ver_code)
    TextView tvVerCode;
    @BindView(R.id.tv_next)
    TextView tvNext;

    protected String longitude = "0"; //经度
    protected String latitude = "0"; // 纬度

    private String mOpenid;
    private AbortableFuture<LoginInfo> loginRequestNim;
    //最大倒计时长
    private static final long MAX_COUNT_TIME = 90;
    private Observable<Long> mObservableCountTime;
    private Consumer<Long> mConsumerCountTime;
    //用于主动取消订阅倒计时，或者退出当前页面。
    private Disposable mDisposable;

    public static Intent newIntent(Context context, String openid) {
        Intent intent = new Intent(context, BindActivity.class);
        intent.putExtra(ExtraParam.ID, openid);
        return intent;
    }

    @Override
    protected String getNewTitle() {
        return "绑定手机号";
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_bind;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setNeedOnBus(true);
        mOpenid = getIntent().getStringExtra(ExtraParam.ID);
        initListener();
        countDown();
    }

    private void initListener() {
        MyTextWatcher myTextWatcher = new MyTextWatcher(() -> {
            if (VerifyUtil.isMobileNO(etPhone.getText().toString().trim()) &&
                    etVerCode.getText().toString().trim().length() > 0) {
                tvNext.setEnabled(true);
                tvNext.setBackgroundResource(R.drawable.shape_yellow);
            } else {
                tvNext.setEnabled(false);
                tvNext.setBackgroundResource(R.drawable.shape_line);
            }
        });
        etPhone.addTextChangedListener(myTextWatcher);
        etVerCode.addTextChangedListener(myTextWatcher);
    }

    @OnClick(R.id.tv_next)
    public void next() {
        String mobile = etPhone.getText().toString().trim();
        //String pwd = etPwd.getText().toString().trim();
        BdingReq bdingReq = new BdingReq();
        bdingReq.setOpenid(mOpenid);
        bdingReq.setUser_tel(mobile);
        //bdingReq.setPassword(pwd);
        bdingReq.setLatitude(latitude);
        bdingReq.setLongitude(longitude);
        bdingReq.setJpush_id(CommonUtils.getRegistrationID(this));
        bdingReq.setCode(etVerCode.getText().toString().trim());
        showRunningDialog();
        startTask(CommonBiz.getInstance().bdingTell(bdingReq), userBaseResponse -> {
            ToastHelper.show(this, userBaseResponse.msg);
            if (1 == userBaseResponse.code) {
                // 云信登录
                final String account = userBaseResponse.data.getWuserTel();
                final String token = userBaseResponse.data.getYunToken();
                loginRequestNim = NimUIKit.login(new LoginInfo(account, token), new RequestCallback<LoginInfo>() {
                    @Override
                    public void onSuccess(LoginInfo param) {
                        onLoginDone();

                        DemoCache.setAccount(account);
                        saveLoginInfo(account, token);

                        // 初始化消息提醒配置
                        //initNotificationConfig();

                        ToastHelper.show(BindActivity.this, "登录成功");
                        User user = userBaseResponse.data;
                        CommonUtils.saveUser(BindActivity.this, user);
                        EventBus.getDefault().post(new LoginEvent());
                        finish();
                    }

                    @Override
                    public void onFailed(int code) {
                        onLoginDone();
                        if (code == 302 || code == 404) {
                            ToastHelper.show(BindActivity.this, com.netease.nim.demo.R.string.login_failed);
                        } else {
                            ToastHelper.show(BindActivity.this, "登录失败: " + code);
                        }
                    }

                    @Override
                    public void onException(Throwable exception) {
                        ToastHelper.show(BindActivity.this, com.netease.nim.demo.R.string.login_exception);
                        onLoginDone();
                    }
                });
            }
        });
    }

    private void onLoginDone() {
        loginRequestNim = null;
    }

    private void saveLoginInfo(final String account, final String token) {
        Preferences.saveUserAccount(account);
        Preferences.saveUserToken(token);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLocationEvent(LocationEvent locationEvent) {
        longitude = String.valueOf(locationEvent.longitude);
        latitude = String.valueOf(locationEvent.latitude);
    }

    /**
     * 倒计时
     */
    private void countDown() {
        mObservableCountTime = RxView.clicks(tvVerCode)
                //防止重复点击
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .flatMap(o -> {
                    String phone = etPhone.getText().toString().trim();
                    if (!VerifyUtil.isMobileNO(phone)) {
                        ToastHelper.show(this, "请输入正确的手机号码");
                        return Observable.empty();
                    }
                    return Observable.just(true);
                })
                //将点击事件转换成倒计时事件
                .flatMap(o -> {
                    //更新发送按钮的状态并初始化显现倒计时文字
                    RxView.enabled(tvVerCode).accept(false);
                    RxTextView.text(tvVerCode).accept(MAX_COUNT_TIME + " 秒");
                    tvVerCode.setBackgroundResource(R.drawable.shape_line);
                    //在实际操作中可以在此发送获取网络的请求,,续1s
                    SmsRequest smsRequest = new SmsRequest();
                    String phone = etPhone.getText().toString().trim();
                    smsRequest.setUserTel(phone);
                    startTask(CommonBiz.getInstance().duanxin(smsRequest), smsBaseResponse -> ToastHelper.show(BindActivity.this, smsBaseResponse.msg));
                    return Observable.interval(1, TimeUnit.SECONDS, Schedulers.io())
                            .take(MAX_COUNT_TIME)
                            //将递增数字替换成递减的倒计时数字
                            .map(aLong -> MAX_COUNT_TIME - (aLong + 1));
                })
                //切换到 Android 的主线程。
                .observeOn(AndroidSchedulers.mainThread());

        mConsumerCountTime = aLong -> {
            //当倒计时为 0 时，还原 btn 按钮
            if (aLong == 0) {
                RxView.enabled(tvVerCode).accept(true);
                RxTextView.text(tvVerCode).accept(getString(R.string.resend));
                tvVerCode.setBackgroundResource(R.drawable.shape_yellow);
            } else {
                RxTextView.text(tvVerCode).accept(aLong + " 秒");
                tvVerCode.setBackgroundResource(R.drawable.shape_line);
            }
        };
        //订阅
        mDisposable = mObservableCountTime.subscribe(mConsumerCountTime);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }
}
